var express = require('express');
var router = express.Router();
var multer = require('multer')
require('../utils/cloud_sdk_init.js')
const fs = require('fs').promises;
const CloudSDK = require('leancloud-storage')

// 1. 初始化SDK

// 2. image-tools 进行base64编码

// 3. 构造云文件对象

// 路由接口
const storage = multer.diskStorage({
  destination: function (req, file, cb) {  //指定文件存放路径
    cb(null, 'public/images')
  },
  filename: function (req, file, cb) {  //自定义文件存储名称
    console.log(111,file);
    let type = file.mimetype.split('/')[1]  //文件后缀
    let name = Math.random().toString(35).substring(2) + Date.now() //生成随机且唯一的文件名
    cb(null, `${name}.${type}`)
  }
})
const upload = multer({ storage: storage })

router.post('/upload', upload.single('avatar'),async function(req, res, next) {
  console.log(222,req.file); //获取图片文件处理中间件返回的相关信息
 
  const fileData = await fs.readFile(req.file.path);
  let base64 = fileData.toString('base64');
  base64 = 'data:image/png;base64,'+base64
  console.log(base64);
  let cloudRes = await new CloudSDK.File('avatar.png',{base64}).save()
  let path = `/images/${req.file.filename}`
  let url = cloudRes.attributes.url
  res.send({
    code:1,
    msg:'图片上传成功',
    path,
	url
  })
});


module.exports = router;
